package com.caiback.controller;

import com.caiback.pojo.*;
import com.caiback.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/posts")
public class PostController {

    @Autowired
    private PostService postService;

    @PostMapping("/create")
    public Result createPost(@RequestBody Post post) {
        log.info("创建帖子：{}", post);
        // 处理帖子的创建

        String tableName;

        if ("PostsPage".equals(post.getPage())) {
            tableName = "postspage";
        } else if ("PostsMarket".equals(post.getPage())) {
            tableName = "postsmarket";
        } else if ("PostsRecruit".equals(post.getPage())) {
            tableName = "postsrecruit";
        } else if ("PostsFind".equals(post.getPage())) {
            tableName = "postsfind";
        } else {
            return Result.error("无效的页面");
        }

        // 构造插入数据的 SQL
        String sql = "INSERT INTO " + tableName + " (title, content, user_id, username, createTime, updateTime) " +
                "VALUES (#{post.title}, #{post.content}, #{post.userId}, #{post.username}, now(), now())";

        int result = postService.createPost(sql, post);

        return result > 0 ? Result.success("创建成功") : Result.error("创建失败");
    }

    @GetMapping("/find")
    public List<Post> getPostsFind() {
        log.info("发布帖子:");

        List<Post> posts = postService.getPostsFind();
        
        return posts;
    }

    @GetMapping("/recruit")
    public List<Post> getPostsRecruit() {
        log.info("发布帖子:");

        List<Post> posts = postService.getPostsRecruit();

        return posts;
    }

    @GetMapping("/market")
    public List<Post> getPostsMarket() {
        log.info("发布帖子:");

        List<Post> posts = postService.getPostsMarket();

        return posts;
    }

    @GetMapping("/page/market")
    public List<MarketPost> getPostsPage(Integer userId) {
        log.info("个人跳蚤市场帖子:");

        List<MarketPost> posts = postService.getPostsPageMarket(userId);

        return posts;
    }

    @GetMapping("/page/find")
    public List<FindPost> getPostsPageFind(Integer userId) {
        log.info("个人寻找帖子:");

        List<FindPost> posts = postService.getPostsPageFind(userId);

        return posts;
    }

    @GetMapping("/page/recruit")
    public List<RecruitPost> getPostsPageRecruit(Integer userId) {
        log.info("个人招聘帖子:");

        List<RecruitPost> posts = postService.getPostsPageRecruit(userId);

        return posts;
    }

    @DeleteMapping("/delete/{id}")
    public Result deletePost(@PathVariable("id") Integer id, @RequestParam String postsname) {
        log.info("删除帖子：{}", id);

        int result = postService.deletePost(id, postsname);

        return Result.success("删除成功");
    }
}

